package com.blockmeta.bbs.businesslibrary.decoration;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.annotation.ColorInt;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseAdapter;


/**
 * @author AirThor
 * @date 2018/11/13.
 * 线性垂直方向列表分割线
 */
public class LinearVerticalItemDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int mStartAndEndOffset = 0;
    private int mFirstDrawItem = 0;

    private boolean isDrawLine = true;

    public void setDrawLine(boolean drawLine) {
        isDrawLine = drawLine;
    }

    private int mGap = 1;

    public void setGap(int gap) {
        mGap = gap;
    }

    public LinearVerticalItemDecoration() {
    }

    public LinearVerticalItemDecoration(@ColorInt int color) {
        mPaint.setColor(color);
    }

    public LinearVerticalItemDecoration(@ColorInt int color, int offset) {
        mPaint.setColor(color);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(1);
        mStartAndEndOffset = offset;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        BaseAdapter adapter = (BaseAdapter) parent.getAdapter();
        mFirstDrawItem = adapter.getHeaderLayoutCount();
        if (position > mFirstDrawItem) {
            outRect.set(0,mGap,0,0);
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        if (!isDrawLine){
            return;
        }
        for (int i = 0; i < parent.getChildCount(); i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            if (position>mFirstDrawItem) {
                c.drawLine(mStartAndEndOffset, view.getTop()-1, view.getRight() - mStartAndEndOffset, view.getTop()-1, mPaint);
            }
        }
    }
}
